<!-- 导出PDF -->
<template>
  <el-dialog v-if="props.show" v-model="props.show" :title="props.title" :close-on-click-modal="false"
    :close-on-press-escape="false" width="60%" top="18vh" @close="onHideDetails">
    <el-form :model="data.query" :rules="data.rules" ref="addQuery" status-icon :validate-on-rule-change="false"
      :scroll-to-error="true">
      <form-item title="商户类别" :pass="true" value="operator_id" v-if="!indexStore.is_general_agent">
        <el-select class="formItem240" v-model="data.query.operator_id" placeholder="请选择" filterable
          @change="getCommercialList">
          <el-option label="全部" :value="-1" />
          <el-option class="flexBetween" v-for="item in indexStore.operatorArray" :key="item.value"
            :label="'【' + item.value + '】' + item.label" :value="item.value" v-show="item.status && item.type != 1">
            【{{ item.value }}】{{ item.label }}
            <el-tag size="small" :type="item.value == 1 ? 'success' : item.currency == 1 ? 'danger' : 'warning'"
              style="font-size:10px;">
              {{ item.value == 1 ? '直营' : item.currency == 1 ? '多货币' : '正常总代' }}
            </el-tag>
          </el-option>
        </el-select>
        <span class="tipsText">({{ t('com_1') }})</span>
      </form-item>
      <form-item title="商户" :pass="true" value="agent_ids">
        <el-select class="imWidth100" v-model="data.query.agent_ids" placeholder="请选择" filterable multiple
          @change="chooseAgent">
          <el-option label="全部" :value="-1" />
          <el-option v-for="item in data.commercialArray" :key="item.value" :label="'【' + item.value + '】' + item.label"
            :value="item.value" v-show="!item.type" />
        </el-select>
        <span class="tipsText">(选择导出账单的商户)</span>
      </form-item>
      <form-item title="账单类型">
        <el-radio-group v-model="data.query.calculation" size="large">
          <el-radio-button label="分成账单" :value="0" />
          <el-radio-button label="返佣账单" :value="1" v-if="!indexStore.is_general_agent" />
        </el-radio-group>
      </form-item>
      <form-item title="导出时间段" :pass="true" value="date">
        <div style="width: 350px !important;">
          <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
            end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime" style="width: 350px !important;" />
          <span class="tipsText">(选择导出账单数据的日期)</span>
        </div>
      </form-item>
      <form-item title="钱包">
        <el-select v-model="data.query.type" placeholder="请选择" filterable>
          <el-option v-for="(item, index) in data.addressList" :key="index" :label="item.label" :value="item.value" />
        </el-select>
        <span class="tipsText">(下拉选择TRC20、ERC20、BEP20；默认选择TRC20)</span>
      </form-item>
      <form-item title="钱包地址" value="address">
        <el-input class="width320" v-model="data.query.address" placeholder="请输入" clearable
          onKeyUp="value=value.replace(/[\W]/g,'')" />
        <span class="tipsText">(选填！输入钱包地址，导出后保存地址)</span>
      </form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="warning" :loading="data.loading" @click="exportTypePDF">导出账单</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 账单样式 -->
  <div id="pdfContent" ref="pdfContent" >
    <PdfDocument :show="props.show" :title="data.title" :number="data.query.number" :summation="data.summation" :query="data.query" :list="data.list"/>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import PdfDocument from '@/components/FormItem/PdfDocument.vue'
import { getCommercialTotal } from '@/api/common'
import { throttle, colorClass, selectToLabel, ArrayReduce, StringReplace } from '@/utils/index'
import { BigWan, BigTimes, BigTofixedFour } from '@/utils/math'
import { setTimeValue, getMonth, getDateDay } from '@/utils/time'
import { Time } from '@/utils/serverTime'
import { getWalletAddress, addWalletAddress, getCheckReport } from '@/api/merchant'

import { useI18n } from 'vue-i18n'
const { t } = useI18n()
import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  title: {
    type: String,
    default: () => {
      return ''
    }
  },
})

const data = reactive({
  query: {
    operator_id: -1,
    agent_ids: [-1],
    date: getMonth(0),
    type: 'TRC20',
    address: '',
    number: '',
    calculation: 0
  },
  list: [] as any,
  commercialArray: indexStore.agentArray,
  addressList: [
    { label: 'TRC20', value: 'TRC20' },
    { label: 'ERC20', value: 'ERC20' },
    { label: 'BEP20', value: 'BEP20' },
  ],
  rules: {
    agent_ids: [{ required: true, message: '请选择商户', trigger: 'change' }],
    date: [{ required: true, message: '请选择导出日期', trigger: 'change' }],
  },
  summation: 0,
  loading: false,
  userInfo: JSON.parse(localStorage.getItem('userInfo') as string),
  title: indexStore.BackOperator
})

watch(
  () => props.show,
  async (value) => {
    if (value) {
      getWalletAddressInfo()
    }
  },
  { deep: true }
)

const getSearchList = async () => {
  let queryDetails = JSON.parse(JSON.stringify(data.query));
  queryDetails = setTimeValue(queryDetails)
  const all = data.query.agent_ids.find((item: number) => item == -1)
  if (all) {
    queryDetails.agent_ids = []
    data.commercialArray.forEach((item: any) => {
      queryDetails.agent_ids.push(item.value)
    })
  }
  let res = await getCheckReport(queryDetails);
  // if (res.data) {
  //   if (res.data.bill.length) {
  //     let summy = [] as number[];
  //     data.query.number = res.data.bill_number
  //     res.data.bill?.forEach((item: any, index: number) => {
  //       item.index = index + 1
  //       item.total_game_income = BigWan(item.total_game_income)
  //       item.game_income = BigWan(BigTimes(item.game_income, item.usdt_exchange_rate))
  //       // 汇总
  //       summy.push(item.game_income)
  //       item.total_bet_count = BigTimes(item.total_game_income, item.usdt_exchange_rate)
  //       // 账单
  //       item.total_bet_count = BigTimes(item.total_game_income, item.usdt_exchange_rate)
  //       // 分成账单
  //       if(!data.query.calculation){
  //         item.config_ggr = [], item.ggrKey = Object.keys(item.ggr?item.ggr:[])
  //         item.ggrKey.forEach((key: number) => {
  //           item.config_ggr.push({ platform: Number(key), radio: item.ggr[Number(key)], })
  //         })
  //       }
  //     })
  //     data.list = res.data.bill
  //     // 汇总
  //     data.summation = BigTofixedFour(ArrayReduce(summy))
  //     nextTick(() => {
  //       exportPDF()
  //     })
  //   } else {
  //     ElMessage.error('导出商户无数据')
  //   }
  // } else {
  //   ElMessage.error('导出商户无数据')
  // }
    let BillKeys=Object.keys(res.data)
    if(!res.data){
      ElMessage.error('导出商户无数据')
    }
    BillKeys.forEach((key:string)=> {
      // 账单订单号
      data.query.number = setBillingNumber(key)
      data.list = []
      let summy = [] as number[];
      pdfContent.value = null
      // 直营的要分商户导出 非直营的以总代为单位导出
      if(key=='1'){
        res.data[key].forEach((item: any, index: number) => {
          item.index = index + 1
          item.total_game_income = BigWan(item.total_game_income)
          item.game_income = BigWan(BigTimes(item.game_income, item.usdt_exchange_rate))
          // 汇总
          summy.push(item.game_income)
          // 账单
          item.total_bet_count = BigTimes(item.total_game_income, item.usdt_exchange_rate)
          // 分成账单
          if(!data.query.calculation){
            item.config_ggr = [], item.ggrKey = Object.keys(item.ggr?item.ggr:[])
            item.ggrKey.forEach((key: number) => {
              item.config_ggr.push({ platform: Number(key), radio: item.ggr[Number(key)], })
            })
          }
          data.summation = BigTofixedFour(ArrayReduce(summy))
          data.list.push(item)
          nextTick(() => {
            exportPDF(item.agent_id)
          })
        })
      }else{
        res.data[key].forEach((item: any, index: number) => {
          item.index = index + 1
          item.total_game_income = BigWan(item.total_game_income)
          item.game_income = BigWan(BigTimes(item.game_income, item.usdt_exchange_rate))
          // 汇总
          summy.push(item.game_income)
          // 账单
          item.total_bet_count = BigTimes(item.total_game_income, item.usdt_exchange_rate)
          // 分成账单
          if(!data.query.calculation){
            item.config_ggr = [], item.ggrKey = Object.keys(item.ggr?item.ggr:[])
            item.ggrKey.forEach((key: number) => {
              item.config_ggr.push({ platform: Number(key), radio: item.ggr[Number(key)], })
            })
          }
        })
        data.summation = BigTofixedFour(ArrayReduce(summy))
        data.list = res.data[key]
        nextTick(() => {
          exportPDF(key)
        })
      }
      console.log(data.summation,data.list);
    })
  data.loading = false
}

// 账单订单号 = OMG+总代/商户id+当前日期+当前时间戳
const setBillingNumber =(id:string) => {
  return 'OMG'+id+StringReplace(getDateDay(0),'-','')+new Time().toTimestamp()
}

// 获取钱包地址
const getWalletAddressInfo = async () => {
  let res = await getWalletAddress({});
  if (res.data.collection_address) {
    data.query.type = res.data.collection_address
  }
  if (res.data.wallet_address) {
    data.query.address = res.data.wallet_address
  }
}
// 设置钱包地址
const setWalletAddress = async () => {
  await addWalletAddress({
    collection_address: data.query.type,
    wallet_address: data.query.address
  })
}

// 选择总代-查询总代下所有商户
const getCommercialList = async (id: any) => {
  data.query.agent_ids = [-1]
  if(id==-1){
    data.commercialArray = indexStore.is_general_agent ? indexStore.agentArray : indexStore.operatorArray
  }else{
    let res = await getCommercialTotal({ operated_id: id })
    data.commercialArray = res.data as any
  }
}
const chooseAgent = async (row: any) => {
  const all = row.find((item: number) => item == -1)
  if (all) {
    data.query.agent_ids = [-1] as any
  } else {
    data.query.agent_ids = row
  }
}

// 选择导出
const addQuery = ref<FormInstance>()
const exportTypePDF = throttle(async () => {
  if (!addQuery.value) return
  await addQuery.value.validate(async (valid, fields) => {
    if (valid) {
      data.loading = true
      setWalletAddress()
      getSearchList()
    }
  })
}, 2000)

// 导出PDF
const pdfContent = ref();
const exportPDF = async (id?:string) => {
  const content = pdfContent.value;
  // 使用 html2canvas 将页面元素转换为画布
  const canvas = await html2canvas(content);
  // 创建一个新的jspdf实例
  const pdf = new jsPDF('l', 'mm', 'a4');
  // 将画布转换为图片
  const img = canvas.toDataURL('image/png');
  // 将图片添加到PDF中
  const imgProps = pdf.getImageProperties(img);
  const pdfWidth = pdf.internal.pageSize.getWidth();
  const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
  // if(pdfHeight < canvas.height){
  //   pdf.addPage(); //如果后面还有内容，添加一个空页
  // }
  pdf.addImage(img, 'PNG', 0, 0, pdfWidth, pdfHeight);
  // 保存生成的PDF
  // pdf.save(`${data.title}账单${data.query.date[0].slice(0, 7)}_${selectToLabel(indexStore.operatorArray, data.query.operator_id)}.pdf`);
  pdf.save(`${data.title}账单${data.query.date[0].slice(0, 7)}_${selectToLabel(indexStore.operatorArray, id)?selectToLabel(indexStore.operatorArray, id):selectToLabel(indexStore.agentArray, id)}.pdf`);
  // exportAsPDF()
};

const exportAsPDF = async () => {
  const element = pdfContent.value;
  const canvas = await html2canvas(element, { scale: 2 });
  const imgData = canvas.toDataURL('image/png');
  const pdf = new jsPDF({
    orientation: 'portrait',
    unit: 'px',
    format: 'a4',
  })
 
  const imgProps= pdf.getImageProperties(imgData);
  const pdfWidth = pdf.internal.pageSize.getWidth();
  const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
  let heightLeft = pdfHeight;
 
  const pageHeight = pdf.internal.pageSize.getHeight();
  let position = 0;
 
  pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pdfHeight);
 
  while (heightLeft > 0) {
    heightLeft -= pageHeight;
    position -= pageHeight;
    if (heightLeft > 0) {
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pageHeight);
    } else {
      pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pageHeight + heightLeft);
    }
  }
  pdf.save(`测试.pdf`)
}
// 重置
const emit = defineEmits(['onHideDetails'])
const onHideDetails = () => {
  data.query = {
    operator_id: -1,
    agent_ids: [-1],
    date: getMonth(0),
    type: 'TRC20',
    address: '',
    number: '',
    calculation: 0
  }
  emit('onHideDetails', false)
}
defineExpose({
  exportPDF
})
</script>

<style scoped lang="scss">
@font-face {
  font-family: 'YaHei';
  src: url(@/assets/font/msyhl.ttc);
  font-weight: normal;
  font-style: normal;
}

.fontWeight {
  font-weight: 600 !important;
}

.fontSize16 {
  font-size: 16px !important;
}

.pdf {
  font-size: 21px;
  padding: 20px 40px;
  font-family: 'YaHei', sans-serif;

  .box-title {
    font-size: 34px;
    color: #0e8a88;
  }

  .summation {
    width: 270px;

    .width200 {
      border-radius: 3px;
      padding: 5px;
      background-color: #EEEEEE;
    }
  }

  .collection {
    width: 360px;
    font-size: 16px;
    border: 1px solid #dddddd;

    div {
      margin: -1px;
      padding: 5px 0;
      border: 1px solid #dddddd;
    }

    .address {
      color: #000000;
      background-color: #EEEEEE;
    }
  }
}
</style>
<style lang="scss"></style>